package main

import (
	"net"
	"fmt"
	"strings"
)

//处理用户请求
func HandleConn(conn net.Conn)  {
	//获取客户端的网络地址信息
	addr := conn.RemoteAddr().String()
	fmt.Printf("[%s]: 连接成功...\n", addr)

	defer conn.Close()
	//读取用户数据
	buf := make([]byte, 2048)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("err = ", err)
			return
		}
		word := strings.Trim(string(buf[:n]), "\r\n")
		fmt.Printf("[%s]: %s\n", addr, word)

		if word == "exit" {
			fmt.Printf("[%s] 离开了...", addr)
			return
		}

		//将输入转换为大写
		conn.Write([]byte(strings.ToUpper(word)))
	}

}

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err = ", err)
		return
	}
	fmt.Println("服务启动成功...")

	defer listener.Close()

	//接收多个用户
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("err = ", err)
			return
		}

		//处理用户请求
		go HandleConn(conn)
	}
}
